let strategies = JSON.parse(localStorage.getItem('tradingStrategies')) || [];

// 自定义字段存储
let customFields = JSON.parse(localStorage.getItem('customFields') || '[]');

// 示例股票数据
const sampleStockData = [
    { code: '600000', name: '浦发银行', open: 10.2, close: 10.5, high: 10.8, low: 10.1, volume: 500000 },
    { code: '600036', name: '招商银行', open: 35.6, close: 36.2, high: 36.5, low: 35.3, volume: 300000 },
    { code: '601318', name: '中国平安', open: 48.3, close: 47.8, high: 48.7, low: 47.5, volume: 800000 }
];


// 数学函数扩展
const mathFunctions = {
    log: Math.log,
    log10: Math.log10,
    exp: Math.exp,
    sqrt: Math.sqrt,
    pow: Math.pow,
    abs: Math.abs
};

export function renderStrategyList() {
    const tbody = document.getElementById('strategy-list');
    if (!tbody) return; // 如果不在策略页面则返回
    
    if (strategies.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="p-3 text-center text-gray-500">
                    暂无策略
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = strategies.map(strategy => `
        <tr>
            <td class="p-3">${strategy.name}</td>
            <td class="p-3">${getStrategyTypeName(strategy.type)}</td>
            <td class="p-3">
                <span class="px-2 py-1 rounded-full text-xs ${strategy.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                    ${strategy.active ? '运行中' : '已停止'}
                </span>
            </td>
            <td class="p-3">0.00%</td>
            <td class="p-3 space-x-2">
                <button class="text-blue-500 edit-strategy-btn" data-id="${strategy.id}">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="text-green-500 toggle-strategy-btn" data-id="${strategy.id}">
                    ${strategy.active ? '<i class="fas fa-pause"></i>' : '<i class="fas fa-play"></i>'}
                </button>
                <button class="text-red-500 delete-strategy-btn" data-id="${strategy.id}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
    
    // 绑定编辑、切换和删除事件
    document.querySelectorAll('.edit-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            editStrategy(strategyId);
        });
    });
    
    document.querySelectorAll('.toggle-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            toggleStrategy(strategyId);
        });
    });
    
    document.querySelectorAll('.delete-strategy-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-id');
            deleteStrategy(strategyId);
        });
    });
}

function getStrategyTypeName(type) {
    const types = {
        'turtle': '海龟交易',
        'golden_cross': '均线金叉',
        'moving_average': '均线策略',
        'custom': '自定义'
    };
    return types[type] || '未知';
}

// 渲染自定义字段列表
export function renderCustomFieldsList() {
    const container = document.getElementById('custom-fields-list');
    if (!container) return;
    
    if (customFields.length === 0) {
        container.innerHTML = '<tr><td colspan="3" class="p-3 text-center text-gray-500">暂无自定义字段</td></tr>';
        return;
    }
    
    container.innerHTML = customFields.map(field => `
        <tr>
            <td class="p-3 border">${field.name}</td>
            <td class="p-3 border font-mono text-sm">${field.formula}</td>
            <td class="p-3 border">
                <button class="remove-field-btn bg-red-500 text-white px-2 py-1 rounded text-sm" 
                        data-field-id="${field.id}">
                    删除
                </button>
            </td>
        </tr>
    `).join('');
    
    // 绑定删除事件
    document.querySelectorAll('.remove-field-btn').forEach(button => {
        button.addEventListener('click', function() {
            const fieldId = this.getAttribute('data-field-id');
            customFields = customFields.filter(f => f.id !== fieldId);
            localStorage.setItem('customFields', JSON.stringify(customFields));
            renderCustomFieldsList();
            renderPreviewTable();
        });
    });
}

// 渲染预览表格
export function renderPreviewTable() {
    // 更新表头
    const headerRow = document.getElementById('preview-table-header');
    if (!headerRow) return;
    
    let headerHtml = `
        <th class="p-2 border">代码</th>
        <th class="p-2 border">名称</th>
        <th class="p-2 border">开盘价</th>
        <th class="p-2 border">收盘价</th>
        <th class="p-2 border">最高价</th>
        <th class="p-2 border">最低价</th>
        <th class="p-2 border">成交量</th>
    `;
    
    // 添加自定义字段列
    customFields.forEach(field => {
        headerHtml += `<th class="p-2 border">${field.name}</th>`;
    });
    
    headerRow.innerHTML = headerHtml;
    
    // 更新表体
    const bodyContainer = document.getElementById('preview-table-body');
    if (!bodyContainer) return;
    
    bodyContainer.innerHTML = sampleStockData.map(stock => {
        let rowHtml = `
            <tr>
                <td class="p-2 border">${stock.code}</td>
                <td class="p-2 border">${stock.name}</td>
                <td class="p-2 border">${stock.open}</td>
                <td class="p-2 border">${stock.close}</td>
                <td class="p-2 border">${stock.high}</td>
                <td class="p-2 border">${stock.low}</td>
                <td class="p-2 border">${stock.volume}</td>
        `;
        
        // 计算并添加自定义字段值
        customFields.forEach(field => {
            try {
                const value = evaluateFormula(field.formula, stock, sampleStockData);
                rowHtml += `<td class="p-2 border">${typeof value === 'number' ? value.toFixed(4) : value}</td>`;
            } catch (e) {
                rowHtml += `<td class="p-2 border text-red-500">Error</td>`;
            }
        });
        
        rowHtml += '</tr>';
        return rowHtml;
    }).join('');
}

// 设置字段管理事件监听器
export function setupFieldManagementEvents() {
    const addFieldBtn = document.getElementById('add-field-btn');
    if (addFieldBtn) {
        addFieldBtn.addEventListener('click', function() {
            const fieldName = document.getElementById('new-field-name')?.value.trim();
            const formula = document.getElementById('field-formula')?.value.trim();
            
            if (!fieldName || !formula) {
                alert('请输入字段名称和公式');
                return;
            }
            
            // 验证公式
            try {
                // 创建测试数据
                const testData = sampleStockData[0];
                const allData = sampleStockData;
                
                // 解析并测试公式
                evaluateFormula(formula, testData, allData);
                
                // 添加新字段
                customFields.push({
                    id: fieldName.toLowerCase().replace(/\s+/g, '_'),
                    name: fieldName,
                    formula: formula
                });
                
                // 保存到localStorage
                localStorage.setItem('customFields', JSON.stringify(customFields));
                
                // 更新UI
                renderCustomFieldsList();
                renderPreviewTable();
                
                // 清空输入
                if (document.getElementById('new-field-name')) {
                    document.getElementById('new-field-name').value = '';
                }
                if (document.getElementById('field-formula')) {
                    document.getElementById('field-formula').value = '';
                }
            } catch (e) {
                alert('公式错误: ' + e.message);
            }
        });
    }
}

// 设置策略编辑器事件监听器
export function setupStrategyEditorEvents() {
    // 策略模板选择
    const strategyTemplate = document.getElementById('strategy-template');
    if (strategyTemplate) {
        strategyTemplate.addEventListener('change', function() {
            // 隐藏所有参数面板
            document.querySelectorAll('.strategy-params').forEach(el => {
                el.classList.add('hidden');
            });
            
            // 显示选中的参数面板
            const template = this.value;
            if (template) {
                const paramsElement = document.getElementById(`${template}-params`);
                if (paramsElement) {
                    paramsElement.classList.remove('hidden');
                }
            }
        });
    }
    
    // 代码编辑器语言标签切换
    const languageTabs = document.querySelectorAll('#strategy-page .border-b button');
    languageTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有标签的激活状态
            languageTabs.forEach(t => t.classList.remove('bg-gray-100'));
            // 添加当前标签的激活状态
            this.classList.add('bg-gray-100');
        });
    });
    
    // 加载模板按钮
    const loadTemplateBtn = document.getElementById('load-template-btn');
    if (loadTemplateBtn) {
        loadTemplateBtn.addEventListener('click', function() {
            const template = document.getElementById('strategy-template')?.value;
            const strategyName = document.getElementById('strategy-name')?.value || '新策略';
            
            let codeTemplate = '';
            switch(template) {
                case 'turtle':
                    codeTemplate = `/* 海龟交易策略
 * 基于突破的交易系统，使用ATR止损
 */
function turtleStrategy(data, params) {
    const breakoutDays = params.breakoutDays || 20;
    const atrMultiplier = params.atrMultiplier || 2;
    const positionRatio = params.positionRatio || 1;
    
    // 计算过去N天的最高价和最低价
    const highs = data.high.slice(-breakoutDays);
    const lows = data.low.slice(-breakoutDays);
    const highestHigh = Math.max(...highs);
    const lowestLow = Math.min(...lows);
    
    // 计算ATR
    const atr = calculateATR(data, 14);
    
    const lastClose = data.close[data.close.length - 1];
    
    // 入场信号
    if (lastClose > highestHigh) {
        return {
            action: 'buy',
            price: highestHigh,
            stopLoss: highestHigh - (atr * atrMultiplier),
            positionSize: positionRatio
        };
    } else if (lastClose < lowestLow) {
        return {
            action: 'sell',
            price: lowestLow,
            stopLoss: lowestLow + (atr * atrMultiplier),
            positionSize: positionRatio
        };
    }
    
    return null;
}

// 计算ATR函数
function calculateATR(data, period) {
    let tr = [];
    for (let i = 1; i < data.close.length; i++) {
        const todayHigh = data.high[i];
        const todayLow = data.low[i];
        const yesterdayClose = data.close[i-1];
        
        const tr1 = todayHigh - todayLow;
        const tr2 = Math.abs(todayHigh - yesterdayClose);
        const tr3 = Math.abs(todayLow - yesterdayClose);
        
        tr.push(Math.max(tr1, tr2, tr3));
    }
    
    // 计算ATR
    let atr = tr.slice(0, period).reduce((a, b) => a + b, 0) / period;
    for (let i = period; i < tr.length; i++) {
        atr = (atr * (period - 1) + tr[i]) / period;
    }
    
    return atr;
}`;
                    break;
                    
                case 'golden_cross':
                    codeTemplate = `/* 均线金叉策略
 * 当短期均线上穿长期均线时买入，下穿时卖出
 */
function goldenCrossStrategy(data, params) {
    const shortPeriod = params.shortPeriod || 5;
    const longPeriod = params.longPeriod || 10;
    const volumeThreshold = params.volumeThreshold || 1000;
    
    // 计算均线
    const shortMA = calculateMA(data.close, shortPeriod);
    const longMA = calculateMA(data.close, longPeriod);
    
    const lastShortMA = shortMA[shortMA.length - 1];
    const lastLongMA = longMA[longMA.length - 1];
    const prevShortMA = shortMA[shortMA.length - 2];
    const prevLongMA = longMA[longMA.length - 2];
    
    const lastVolume = data.volume[data.volume.length - 1];
    
    // 金叉买入信号
    if (lastShortMA > lastLongMA && prevShortMA <= prevLongMA && lastVolume >= volumeThreshold) {
        return {
            action: 'buy',
            price: data.close[data.close.length - 1],
            comment: '均线金叉'
        };
    }
    
    // 死叉卖出信号
    if (lastShortMA < lastLongMA && prevShortMA >= prevLongMA) {
        return {
            action: 'sell',
            price: data.close[data.close.length - 1],
            comment: '均线死叉'
        };
    }
    
    return null;
}

// 计算简单移动平均线
function calculateMA(data, period) {
    let ma = [];
    for (let i = period - 1; i < data.length; i++) {
        const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
        ma.push(sum / period);
    }
    return ma;
}`;
                    break;
                    
                case 'moving_average':
                    codeTemplate = `/* 均线回归策略
 * 当价格偏离均线一定比例时进行反向操作
 */
function movingAverageStrategy(data, params) {
    const period = params.period || 10;
    const deviationPercent = params.deviationPercent || 2;
    
    // 计算均线
    const ma = calculateMA(data.close, period);
    const lastMA = ma[ma.length - 1];
    const lastClose = data.close[data.close.length - 1];
    
    // 计算偏离比例
    const deviation = (lastClose - lastMA) / lastMA * 100;
    
    // 超卖买入信号
    if (deviation < -deviationPercent) {
        return {
            action: 'buy',
            price: lastClose,
            comment: '价格低于均线' + Math.abs(deviation).toFixed(2) + '%'
        };
    }
    
    // 超买卖出信号
    if (deviation > deviationPercent) {
        return {
            action: 'sell',
            price: lastClose,
            comment: '价格高于均线' + deviation.toFixed(2) + '%'
        };
    }
    
    return null;
}

// 计算简单移动平均线
function calculateMA(data, period) {
    let ma = [];
    for (let i = period - 1; i < data.length; i++) {
        const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
        ma.push(sum / period);
    }
    return ma;
}`;
                    break;
                    
                default:
                    codeTemplate = `/* 
 * 自定义策略模板
 * 可用变量:
 * - data: 包含open,high,low,close,volume等历史数据
 * - params: 自定义参数对象
 */

function customStrategy(data, params) {
    /* 可用数据:
    - data.open: 开盘价数组
    - data.high: 最高价数组
    - data.low: 最低价数组
    - data.close: 收盘价数组
    - data.volume: 成交量数组
    - params: 策略参数对象
    */
    
    // 示例策略逻辑
    const lastClose = data.close[data.close.length - 1];
    const prevClose = data.close[data.close.length - 2];
    
    if (lastClose > prevClose) {
        return {
            signal: 'BUY',
            price: lastClose,
            comment: '价格上涨趋势'
        };
    }
    
    return null;
}`;
            }
            
            const strategyCode = document.getElementById('strategy-code');
            if (strategyCode) {
                strategyCode.value = codeTemplate;
            }
        });
    }
    
    // 保存策略按钮
    const saveStrategyBtn = document.getElementById('save-strategy-btn');
    if (saveStrategyBtn) {
        saveStrategyBtn.addEventListener('click', function() {
            const strategyName = document.getElementById('strategy-name')?.value || '未命名策略';
            const strategyCode = document.getElementById('strategy-code')?.value;
            const strategyTemplate = document.getElementById('strategy-template')?.value;
            
            // 收集参数
            const params = {};
            if (strategyTemplate === 'turtle') {
                params.breakoutDays = document.querySelector('#turtle-params input:nth-child(2)')?.value || 20;
                params.atrMultiplier = document.querySelector('#turtle-params input:nth-child(4)')?.value || 2;
                params.positionRatio = document.querySelector('#turtle-params input:nth-child(6)')?.value || 1;
            } else if (strategyTemplate === 'golden_cross') {
                params.shortPeriod = document.querySelector('#golden-cross-params input:nth-child(2)')?.value || 5;
                params.longPeriod = document.querySelector('#golden-cross-params input:nth-child(4)')?.value || 10;
                params.volumeThreshold = document.querySelector('#golden-cross-params input:nth-child(6)')?.value || 1000;
            } else if (strategyTemplate === 'moving_average') {
                params.period = document.querySelector('#moving-average-params input:nth-child(2)')?.value || 10;
                params.deviationPercent = document.querySelector('#moving-average-params input:nth-child(4)')?.value || 2;
            }
            
            // 创建新策略对象
            const newStrategy = {
                id: Date.now().toString(),
                name: strategyName,
                type: strategyTemplate || 'custom',
                code: strategyCode,
                params: params,
                active: false,
                createdAt: new Date().toISOString(),
                performance: []
            };
            
            // 保存到策略列表
            strategies.push(newStrategy);
            localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
            
            // 更新策略列表显示
            renderStrategyList();
            
            alert('策略保存成功！');
        });
    }
    
    // 验证策略按钮
    const validateStrategyBtn = document.getElementById('validate-strategy-btn');
    if (validateStrategyBtn) {
        validateStrategyBtn.addEventListener('click', function() {
            const strategyCode = document.getElementById('strategy-code')?.value;
            
            try {
                // 简单验证代码语法
                new Function(strategyCode);
                alert('策略代码语法正确！');
            } catch (e) {
                alert('策略代码存在语法错误：' + e.message);
            }
        });
    }
}

// 解析并计算公式
function evaluateFormula(formula, rowData, allData) {
    try {
        // 替换数学函数调用
        let processedFormula = formula.replace(
            /(log|log10|exp|sqrt|pow|abs)\(/g, 
            'mathFunctions.$1('
        );
        
        // 替换quant函数调用
        processedFormula = processedFormula.replace(
            /(rank|scale|corr)\(/g, 
            'quantFunctions.$1('
        );
        
        // 创建计算函数
        const calcFunction = new Function(
            'row', 
            'mathFunctions', 
            'quantFunctions', 
            'allData', 
            `return ${processedFormula};`
        );
        
        return calcFunction(rowData, mathFunctions, quantFunctions, allData);
    } catch (e) {
        throw new Error('公式解析失败: ' + e.message);
    }
}

// Quantitative functions
const quantFunctions = {
    rank: (arr, value) => {
        const sorted = [...arr].sort((a, b) => a - b);
        return sorted.indexOf(value) + 1;
    },
    scale: (value, min, max) => {
        return (value - min) / (max - min);
    },
    corr: (arr1, arr2, window) => {
        const slice1 = arr1.slice(-window);
        const slice2 = arr2.slice(-window);
        const mean1 = slice1.reduce((a, b) => a + b, 0) / window;
        const mean2 = slice2.reduce((a, b) => a + b, 0) / window;
        let cov = 0, std1 = 0, std2 = 0;
        for(let i = 0; i < window; i++) {
            cov += (slice1[i] - mean1) * (slice2[i] - mean2);
            std1 += Math.pow(slice1[i] - mean1, 2);
            std2 += Math.pow(slice2[i] - mean2, 2);
        }
        return cov / (Math.sqrt(std1) * Math.sqrt(std2));
    }
};

// 编辑策略
function editStrategy(strategyId) {
    const strategy = strategies.find(s => s.id === strategyId);
    if (!strategy) return;
    
    // 填充表单
    const strategyNameInput = document.getElementById('strategy-name');
    const strategyTemplateSelect = document.getElementById('strategy-template');
    const strategyCodeTextarea = document.getElementById('strategy-code');
    
    if (strategyNameInput) strategyNameInput.value = strategy.name;
    if (strategyTemplateSelect) strategyTemplateSelect.value = strategy.type;
    if (strategyCodeTextarea) strategyCodeTextarea.value = strategy.code;
    
    // 显示对应参数面板
    document.querySelectorAll('.strategy-params').forEach(el => {
        el.classList.add('hidden');
    });
    
    if (strategy.type) {
        const paramsElement = document.getElementById(`${strategy.type}-params`);
        if (paramsElement) {
            paramsElement.classList.remove('hidden');
        }
        
        // 填充参数值
        if (strategy.type === 'turtle') {
            const input2 = document.querySelector('#turtle-params input:nth-child(2)');
            const input4 = document.querySelector('#turtle-params input:nth-child(4)');
            const input6 = document.querySelector('#turtle-params input:nth-child(6)');
            
            if (input2) input2.value = strategy.params.breakoutDays || 20;
            if (input4) input4.value = strategy.params.atrMultiplier || 2;
            if (input6) input6.value = strategy.params.positionRatio || 1;
        } else if (strategy.type === 'golden_cross') {
            const input2 = document.querySelector('#golden-cross-params input:nth-child(2)');
            const input4 = document.querySelector('#golden-cross-params input:nth-child(4)');
            const input6 = document.querySelector('#golden-cross-params input:nth-child(6)');
            
            if (input2) input2.value = strategy.params.shortPeriod || 5;
            if (input4) input4.value = strategy.params.longPeriod || 10;
            if (input6) input6.value = strategy.params.volumeThreshold || 1000;
        } else if (strategy.type === 'moving_average') {
            const input2 = document.querySelector('#moving-average-params input:nth-child(2)');
            const input4 = document.querySelector('#moving-average-params input:nth-child(4)');
            
            if (input2) input2.value = strategy.params.period || 10;
            if (input4) input4.value = strategy.params.deviationPercent || 2;
        }
    }
}

// 切换策略状态
function toggleStrategy(strategyId) {
    strategies = strategies.map(strategy => {
        if (strategy.id === strategyId) {
            strategy.active = !strategy.active;
        }
        return strategy;
    });
    
    localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
    renderStrategyList();
}

// 删除策略
function deleteStrategy(strategyId) {
    if (confirm('确定要删除这个策略吗？')) {
        strategies = strategies.filter(strategy => strategy.id !== strategyId);
        localStorage.setItem('tradingStrategies', JSON.stringify(strategies));
        renderStrategyList();
    }
}

